<?php
    @session_start();
    require_once 'shared-functions.php';
    require_once 'session.php';
    require_once 'masterpage.php';
    
    if(!IsValidSession())
    {
        header('Location: login.php?page=notifications');
        exit();
    }
    else
    {
    	RefreshSession();
    }

    $user = GetCurrentUserAccessLevel();

    //Check user access
    if ($user != $DIRECTOR && $user != $ADMIN && $user != $PRINCIPLE) {
        header('Location: login.php?page=notifications&error=To access to the notifications page, please log in as a director, admin&logout=1');
        exit();
    }

    masterpage("Notifications");
	displayDefaultMessage();
	
	//javascript for showing and hiding tables
	echo '<script type="text/javascript">function showNhideTable(table){ if(table.className == "ShowTable"){table.className = "HideTable"}else{table.className = "ShowTable"}}</script>';	
	
	function displayDefaultMessage()
	{
		echo '<table id="defaultMessageTable" name="defaultMessageTable" class="ShowTable"';
		echo '<tr><td>No recent notifications to display<td><tr>';
		echo '</table><br><br>';
	}
	
	function hideTable($Table)
	{
		echo '<script type="text/javascript">document.getElementById("'.$Table.'").style.display = "None";</script>';
	}
		
	function changeDateFormat($cdate){

		list($year,$month,$day)=explode("-",$cdate);

		return $day."/".$month."/".$year;
	}

	function buildNotifications()
	{
		$RecentNotificationsLink = connect_db();	
		$result = mysql_query("SELECT COUNT(*) FROM Notifications WHERE Acknowledgement IS NULL")
			or die("Recent Notification Count Query Failed: " . mysql_error());
		
		$NumRecentNotifications = mysql_result($result,0);
		mysql_close($RecentNotificationsLink);
		
		if ($NumRecentNotifications > 0)
		{
			hideTable("defaultMessageTable");
			
			//***Get Recent Data***
			$link = connect_db();
			$query = mysql_query("SELECT * FROM Applicant, Notifications WHERE Applicant.ApplicantID = Notifications.ApplicantID AND Notifications.Acknowledgement IS NULL")
				or die("Select query failed while building notifications:" . mysql_error());
			mysql_close($link);
			
			//***Process Data and populate list***
			$TableNum = 1;
			while ($info = mysql_fetch_array($query))
			{
				$info['NotificationDate'] = changeDateFormat($info['NotificationDate']);
			
				echo '<form id="NotificationForm" action="notifications.php" method="post">';
				echo '<table id="NotificationTable" name="NotificationTable" style="cursor:pointer;cursor:hand" class="HideTable" onclick="showNhideTable(this)">';
				echo '<tr><th colspan="2">' . $info['Surname'] . ' has submitted an application on ' . $info['NotificationDate'] . '.</th>';
				echo '<th><button name="dismiss" type="submit" value="'.$TableNum.'">Dismiss Notification</button></th></tr>';
				//Note: the following rows are initially hidden from view
				echo '<tr colspan"3"><td>Address: ' . $info['Address'] . '</td></tr>';
				echo '<tr><td colspan"2">E-Mail: ' . $info['Email'] . '</td><td>Phone: ' . $info['Telephone'] . '</td></tr>';
				echo '<tr colspan="3"><td>Intended Program of Study: ' . $info['Program'] . '</td></tr>';
				echo "<tr colspan='3' align='right'><td><a href='applicant-info.php?ApplicantID=" . $info['ApplicantID'] . "' target='_blank'>View Full Application</a></td></tr>";
				echo '<input type="hidden" id="notificationID'.$TableNum.'" name="notificationID'.$TableNum.'" value="'.$info['NotificationsID'].'" />'; //Saves notificationID on postback for dismissing notifications
				echo '</table>';
				echo '<br/><br/>';
				echo '</form>';
				
				$TableNum = $TableNum + 1;
			}
		}
	}
	
	//checks if postback has occured
	//if it has, update DB (also effectivly hides notification)
	if (isset($_POST['dismiss']))
	{
		$SubmitValue = $_POST['dismiss'];
		dismissNotification($_POST['notificationID'.$SubmitValue]);
	}

	//***Updates Notification Data***
	function dismissNotification($NotificationID)
	{		
		$link = connect_db();
		mysql_query("UPDATE Notifications SET Acknowledgement=NOW() WHERE NotificationsID ='".$NotificationID."'")
			or die("Update query failed while dismissing notification:" . mysql_error());
		mysql_close($link);
	}
	
	//***Tests to see if the local machine is connected to the web***
	//uses sockets to open a connection to google.com
	function  testInternetConnection()
	{
		$connected = @fsockopen("www.google.com", 80);
		if ($connected){
			fclose($connected);
			return true;
		}
		
		return false; 
	}

	if (testInternetConnection())
		buildNotifications();
    
    endmasterpage();
?>